package legumes.client.ui.basket.grids;

import java.util.LinkedHashMap;
import java.util.List;

import legumes.client.evt.customer.CustomerOrderChangedEvent;
import legumes.client.evt.manager.EventBusManager;
import legumes.shared.domain.MenuCount;
import legumes.shared.domain.MenuItem;
import legumes.shared.domain.OrderPart;
import legumes.shared.domain.OrderPartMenuItem;
import legumes.shared.domain.SellSessionForCustomer;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.RecordSummaryFunctionType;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.types.SummaryFunctionType;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.RadioGroupItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.HeaderSpan;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.SummaryFunction;
import com.smartgwt.client.widgets.grid.events.EditorExitEvent;
import com.smartgwt.client.widgets.grid.events.EditorExitHandler;
import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler;
import com.smartgwt.client.widgets.grid.events.SelectionEvent;
import com.smartgwt.client.widgets.layout.VLayout;

public class BasketInsidePanel extends VLayout {

	private ListGrid basketGrid;
	private RadioGroupItem radioGroupItem;
	private SellSessionForCustomer sellSessionForCustomer;
	private OrderPart op;
	private LinkedHashMap<String, String> radionMenuCountList;
	
	public BasketInsidePanel() {
		super();
		setWidth100();
		setHeight("50%");
        
		setShowEdges(true);
		setMembersMargin(5);  
        setLayoutMargin(10); 
        
		build();
	}
	
	public void initData(SellSessionForCustomer ssfc_, OrderPart op_){
		op = op_;
		displaySellSessionForCustomer(ssfc_);
	}
	
	protected void displaySellSessionForCustomer(
			SellSessionForCustomer sellSessionForCustomer_) {
		sellSessionForCustomer = sellSessionForCustomer_;
		NumberFormat nf = NumberFormat.getFormat("0.00");
		String wholePrice = nf.
				format(sellSessionForCustomer.getStall().getMenu().getWholePrice());
		String halfPrice = nf.
		format(sellSessionForCustomer.getStall().getMenu().getHalfPrice());

		radionMenuCountList.clear();
        String wholeRadioValue = "Panier entier (" + wholePrice + " &#8364;).";
        radionMenuCountList.put("1", wholeRadioValue);  
        radionMenuCountList.put("0.5", "Demi panier (" + halfPrice + " &#8364;).");  
        radionMenuCountList.put("0", "Aucun panier.");
        radioGroupItem.setValueMap(radionMenuCountList.values().toArray(new String[0]));
        radioGroupItem.setDefaultValue( wholeRadioValue );
        
        List<MenuItem> menuItemList = sellSessionForCustomer.getStall().getMenu().getMenuWholeItems();
		ListGridRecord [] records = new ListGridRecord[menuItemList.size()];
    	int i=0;
    	for (MenuItem p : menuItemList) {
			try{
				ListGridRecord record = new ListGridRecord();
				record.setAttribute("isSelected", true);
				record.setAttribute("prix", p.getOnSaleProduct().getPrice().getAmount());
				record.setAttribute("libelle", p.getArticleName());
				record.setAttribute("quantite", p.getQuantity().getValue());
				record.setAttribute("quantiteUnit", p.getQuantity().getUnitAsEnum().getDisplayName() );
//				if(p!= null && p.getOnSaleProduct() != null && p.getOnSaleProduct().getProduct() != null 
//						&&  p.getOnSaleProduct().getProduct().getProductType() != null){
//					record.setAttribute("categorie", p.getOnSaleProduct().getProduct().getProductType() );
//				} else {
//					record.setAttribute("categorie", "L");
//				}
				records[i] = record;
				i++;
			} catch (NullPointerException e_) {
				GWT.log("Err on displaySellSessionForCustomer ", e_);
			}
		}
    	
    	basketGrid.setRecords(records);
    	
    	basketGrid.selectAllRecords();
	}
	
	private void build(){

        final DynamicForm form = new DynamicForm();  
        form.setWidth100();  
        form.setHeight(21);
//        form.setNumCols(2);  
        form.setTitleWidth(150);
        
        radioGroupItem = new RadioGroupItem("panierRadioGroup", "Panier de la semaine");
        
        radionMenuCountList = new LinkedHashMap<String, String>();  
        radionMenuCountList.put("1", "Panier entier (loading &#8364;).");  
        radionMenuCountList.put("0.5", "Demi panier (loading &#8364;).");  
        radionMenuCountList.put("0", "Aucun panier.");
       
        radioGroupItem.setValueMap(radionMenuCountList.values().toArray(new String[0]));
        //BUG with styleMap http://forums.smartclient.com/showthread.php?t=13337
//        radioGroupItem.setValueMap(styleMap);
        radioGroupItem.setShowTitle(true);
        radioGroupItem.setWrap(false);
        radioGroupItem.setWrapTitle(false);
        radioGroupItem.setVertical(false);
        
        radioGroupItem.setDefaultValue( "Panier entier (loading &#8364;)." );
        radioGroupItem.addChangedHandler(new ChangedHandler() {
			
			@Override
			public void onChanged(ChangedEvent event) {
				GWT.log("radioGroupItem changed" + event.getValue() + "--" 
						 + event.getItem() );
				//Price is updated with the selected elements in the basket grid
				if( ((String)event.getValue()).toUpperCase().indexOf("ENTIER")>=0 ){
					basketGrid.selectAllRecords();
					op.getOrderPartMenuItem().setMenuCount(MenuCount.ONE_MENU);
				} else if ( ((String)event.getValue()).toUpperCase().indexOf("DEMI")>=0){
					op.getOrderPartMenuItem().setMenuCount(MenuCount.HALF_MENU);
					//TODO : Which one to select ?
				} else {
					basketGrid.deselectAllRecords();
					op.getOrderPartMenuItem().setMenuCount(MenuCount.ZERO_MENU);
				}
				
			}
		});
       
        
        form.setItems(radioGroupItem);
        basketGrid = new ListGrid();
        basketGrid.setShowRollOverCanvas(true);  
        basketGrid.setCanEdit(true);
        basketGrid.setHeaderHeight(40); 
        basketGrid.setWidth100();
        basketGrid.setHeight("50%");  
        basketGrid.setShowAllRecords(true);  
        basketGrid.setCellHeight(22);  
        
        basketGrid.setSelectionType(SelectionStyle.SIMPLE);  
        basketGrid.setSelectionAppearance(SelectionAppearance.ROW_STYLE);
        basketGrid.setEditByCell(false);
        basketGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX); 
        
        basketGrid.setHeaderSpans(  
                 new HeaderSpan("Les l&eacute;gumes du panier", new String[]{"libelle", "prix", "total"})  
               );  
  
        
        ListGridField libelleField = new ListGridField("libelle", "Produit", 100);
        libelleField.setShowGridSummary(true); 
        libelleField.setShowGroupSummary(true); 
        libelleField.setWidth(150);
        libelleField.setCanEdit(false);
        libelleField.setSummaryFunction(new SummaryFunction(){

            @Override
            public Object getSummaryValue(Record[] records_, ListGridField field_) {
                int count = 0;
                for(Record r : records_){
                    if( r.getAttributeAsBoolean("isSelected") ){
                        count++;
                    }
                }
                
                
                return count>1 ? count + " s&eacute;lectionn&eacute;s" : count + " s&eacute;lectionn&eacute;";
            }
            
        });  
        
        ListGridField prixField = new ListGridField("prix", "Prix", 150);
        prixField.setType(ListGridFieldType.FLOAT);
        prixField.setAlign(Alignment.RIGHT);
        prixField.setShowGridSummary(false);
        prixField.setShowGroupSummary(false); 
        prixField.setCanEdit(false);
        prixField.setCellFormatter(new CellFormatter(){

            @Override
            public String format(Object value_, ListGridRecord record_, int rowNum_, int colNum_) {
                if(value_ == null) return null;  
                NumberFormat nf = NumberFormat.getFormat("0.00");
                String valueStr = value_.toString();
                try {  
                    valueStr = nf.format(((Number) value_).floatValue());
                    valueStr += " &#8364;";
                } catch (Exception e) {  
                    return "";  
                }  
                
                String quantiteUnit = record_.getAttribute("quantiteUnit");
                float quantite = record_.getAttributeAsFloat("quantite");
                
                if(quantiteUnit != null){
                    quantiteUnit = quantiteUnit.toUpperCase();
                } else {
                    quantiteUnit = "";
                }
                
                return valueStr == null ? "" : 
                	quantite == 1 ?
                			valueStr + " &frasl; " + quantiteUnit :
                			valueStr + " &frasl; " + quantite + " " + quantiteUnit ;
            }
            
        });
        
        final ListGridField totalField = new ListGridField("total", "Total", 100);
        totalField.setType(ListGridFieldType.FLOAT);
        totalField.setCanEdit(false);
        totalField.setShowGridSummary(true); 
        totalField.setShowGroupSummary(true); 
        totalField.setRecordSummaryFunction(RecordSummaryFunctionType.MULTIPLIER);  
        totalField.setSummaryFunction(SummaryFunctionType.SUM);
        
        totalField.setCellFormatter(new CellFormatter(){

            @Override
            public String format(Object value_, ListGridRecord record_, int rowNum_, int colNum_) {
                double total = 0f;
                if(value_ == null){
                    double prix = 0.0;
                    double qte = 0.0;
                    try{
                        prix = record_.getAttributeAsFloat("prix");
                        qte = record_.getAttributeAsFloat("quantite");
                        total = prix * qte;
                    } catch(Exception e_){
                        
                    }
                } else {
                    try{
                        total = (Double) value_;
                    } catch(Exception e_){
                        
                    }
                }
                NumberFormat nf = NumberFormat.getFormat("0.00");
                String valueStr = "";
                try {  
                    valueStr = nf.format(total);  
                } catch (Exception e) {  
                    return "";  
                }  
                
                return valueStr + " &#8364;";
            }
            
        });
        
        
        basketGrid.addEditorExitHandler(new EditorExitHandler() {  
            public void onEditorExit(EditorExitEvent event) {  
                String fieldName = basketGrid.getFieldName(event.getColNum());  
                if("quantite".equals(fieldName) ){  
                    
                    double prix = 0.0;
                    double qte = 0.0;
                    try{
                        prix = event.getRecord().getAttributeAsFloat("prix");
                        qte = event.getRecord().getAttributeAsFloat("quantite");
                        //TODO Manage quantiteUnit better !
                    } catch(Exception e_){
                        
                    }
                    
                    
                    event.getRecord().setAttribute("total", prix * qte);
                    basketGrid.updateData(event.getRecord());
                    basketGrid.refreshRow(event.getRowNum()-1);  
                }  
            }  
        });  
        
        basketGrid.setFields(libelleField, prixField, totalField );  
        basketGrid.addSelectionChangedHandler(new SelectionChangedHandler(){

            @Override
            public void onSelectionChanged(SelectionEvent event_) {
                Record r = event_.getRecord();
            	float price = r.getAttributeAsFloat("prix");
            	String productName = r.getAttributeAsString("libelle");
            	
            	OrderPartMenuItem opmi = op.getOrderPartMenuItem();
            	MenuItem mi = sellSessionForCustomer.getStall().getMenu().findWholeMenuItemFor(productName);
            	if( ! event_.getState() ){
            		opmi.addRemovedMenuItems(mi);
            	} else {
            		if( opmi.isRemoved(mi) ){
            			opmi.removeRemovedItem(mi);
            		}
            	}
            	
            	EventBusManager.getInstance().getEventBus().fireEvent(
                			new CustomerOrderChangedEvent(event_.getState() , price));
                
            }
            
        });
        
        setMembers(form, basketGrid);
    }
}
